package com.zhj.psi.core.exception;

import com.zhj.psi.core.mvc.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhuhuijun on 2017-8-31 15:06:51
 */
@RestControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {
    private Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e) {
        return new AjaxResult().setCode("9000").setErrorMsg(e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(ServiceException e) {
        return new AjaxResult().setCode("9000").setErrorMsg(e.getMessage());
    }

    @ResponseStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION)
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(HttpServletRequest req, Exception e) {
        AjaxResult result = new AjaxResult(e.getMessage());
        if ("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString())) {
            result.setCode("90001");
            logger.info("超时或未登录", e);
        } else {
            result.setCode("90002");
            logger.info("没有权限", e);
        }
        return result;
    }


}
